from PetNetadmin.serializers import CustomMessageSerializer
from admincharge.models import PetOwner, PetMessage
from utils.pagination import PetMessagePagination
from admincharge.utils.jwt import MyJWTAuthentication

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view


# 获取所有信息并且分页和搜索框
class GetAllCustomList(APIView):
    authentication_classes = [MyJWTAuthentication]
    def get(self, request):
        keyword = request.GET.get('keyword')
        if keyword:
            Custom_all_list = PetOwner.objects.filter(ownerphone__contains=keyword)
        else:
            Custom_all_list = PetOwner.objects.all()
        paginator = PetMessagePagination()
        result_page = paginator.paginate_queryset(Custom_all_list, request)
        serializer = CustomMessageSerializer(instance=result_page, many=True)
        result = {
            'data': serializer.data,
            'code': 2000,
            'msg': '获取成功'
        }
        return paginator.get_paginated_response(result)

    # 添加数据
    def post(self, request):
        get_message = request.data
        # 判断数据库是否已经存在了该手机号
        print(get_message)
        exist_phone = PetOwner.objects.filter(ownerphone=get_message['customphone']).first()
        if exist_phone:
            result = {
                'code': 4000,
                'msg': '抱歉，该手机已经存在，无法添加了'
            }
            return Response(data=result)
        data = {
            'ownername': get_message['customname'],
            'ownersex': int(get_message['customsex']),
            'ownerphone': get_message['customphone'],
            'owneraddress': get_message['customaddress'],
            'pet': get_message['custompet'],
            'created_time': get_message['created_time']
        }
        print('data', data)
        serializer = CustomMessageSerializer(data=data, partial=True)
        if serializer.is_valid(raise_exception=True):
            print(serializer.validated_data)
            serializer.save()
            result = {
                'code': 2000,
                'msg': '添加成功'
            }
            return Response(status=status.HTTP_200_OK, data=result)


# 删除单个数据
@api_view(['POST'])
def deleteOneCustommsg(request, id):
    try:
        customMsg = PetOwner.objects.get(id=id)
        customMsg.delete()
        result = {
            'code': 2000,
            'msg': '删除成功'
        }
        return Response(data=result, status=status.HTTP_200_OK)
    except PetOwner.DoesNotExist:
        return Response({"msg": '当前没有该记录可以删除'}, status=status.HTTP_404_NOT_FOUND)


# 删除多个数据
@api_view(['POST'])
def deleteManyCustommsg(request):
    try:
        ids = request.data['Ids']
        # print(ids)
        for id in ids:
            custom_message = PetOwner.objects.get(id=id)
            custom_message.delete()
        result = {
            'code': 2000,
            'msg': '删除成功'
        }
        return Response(data=result, status=status.HTTP_200_OK)
    except PetOwner.DoesNotExist:
        return Response({"msg": '当前没有该记录可以删除'}, status=status.HTTP_404_NOT_FOUND)


# 添加数据前对pet属性进行检验是否存在
@api_view(['POST'])
def beforeaddvalidate(request):
    pet_name = request.data
    print(pet_name)
    if_exist = PetMessage.objects.filter(petname=pet_name).first()
    print(if_exist == True)
    if if_exist:
        result = {
            'code': 4000,
            'msg': '该宠物已经登记了'

        }
        return Response(result)
    result = {
        'code': 2000,
        "msg": '该宠物不存在'
    }
    return Response(result)

# 编辑数据
@api_view(['POST'])
def editCustomMsg(request):
    try:
        id = request.data['id']
        updateMsg = PetOwner.objects.get(id=id)
        serializer = CustomMessageSerializer(instance=updateMsg, data=request.data)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            result = {
                'code': 2000,
                'msg': '上传保存成功'
            }
        return Response(result)
    except PetOwner.DoesNotExist:
        return Response({"msg": '当前没有该记录可以修改'}, status=status.HTTP_404_NOT_FOUND)
